package com.philips.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.poi.hslf.model.Sheet;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

import com.philips.research.vp.utilities.UtilsVP;
import com.philips.util.Common;
import com.philips.util.HttpTool;
import com.philips.util.Log;

/**
 * philips pins
 * @author fu.yuan 310124879
 */
public class AQIService {
	private static String jsonPath=Common.realPath+"data/json/";
	private static String excelPath=Common.realPath+"data/excel/";
	private static String tempFilePath=Common.realPath+"data/template/shanghai_aqi_temp.xls";
	private static String errorMsg="success";
	/**
	 * 
	 * @param citykey : city key
	 * @return
	 */
	public static String exportAQI(String citykey){
		try {
		String urlaqi = "http://222.73.255.34/?city="+citykey+"&area="+citykey;
		HttpClient client = new HttpClient();
		int connectiontimeout=Integer.parseInt(Common.confProp.get("connectTimeout").toString().trim());
		int sotimeout=Integer.parseInt(Common.confProp.get("soTimeout").toString().trim());
		Boolean isproxy=Boolean.parseBoolean(Common.confProp.get("isproxy").toString().trim());
		client.getHttpConnectionManager().getParams() .setConnectionTimeout(connectiontimeout);
	    client.getHttpConnectionManager().getParams().setSoTimeout(sotimeout);
	    
		if(isproxy){
			String proxyhost=Common.confProp.get("proxy.host").toString().trim();
			int proxyport=Integer.parseInt(Common.confProp.get("proxy.port").toString().trim());
			String proxyuser=Common.confProp.get("proxy.user").toString().trim();
			String proxypwd=Common.confProp.get("proxy.password").toString().trim();
			client.getHostConfiguration().setProxy(proxyhost, proxyport);
			client.getParams().setAuthenticationPreemptive(true);
			client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyuser,proxypwd));
		}
		
	  
		GetMethod getaqi = new GetMethod(urlaqi);
		getaqi.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");// 在头文件中设置转码
		client.executeMethod(getaqi);
		
		String aqijson = getaqi.getResponseBodyAsString();

//		test
//		String aqijson=readFile("c:/temp/aqidata.txt");
		
		String nowdt=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(System.currentTimeMillis());
		String nowtime=new SimpleDateFormat("yyyyMMddhhmmss").format(System.currentTimeMillis());
		String nowdate=new SimpleDateFormat("yyyyMMdd").format(System.currentTimeMillis());
		
		PrintWriter out = UtilsVP.openWriteFile(jsonPath+citykey+nowtime+".txt");
		UtilsVP.writeln(out,aqijson);
		UtilsVP.close(out);
		
		HSSFWorkbook wb=null;
	
				File excelfile=new File(excelPath+citykey+nowdate+".xls");
				if(!excelfile.isFile()){
				    wb=new HSSFWorkbook(new FileInputStream(new File(tempFilePath)));
				}else{
					wb=new HSSFWorkbook(new FileInputStream(excelfile));
				}
				JSONObject jso = new JSONObject(aqijson);
				JSONArray results = (JSONArray) jso.get("result");
				String date="";
				if(results!=null){
				for (int i = 0; i < results.length(); i++) {
					JSONObject resulto=(JSONObject)results.get(i);
					JSONObject citynow=(JSONObject)resulto.get("citynow");
					date=citynow.getString("date");
					JSONObject lastMoniData=(JSONObject)resulto.get("lastMoniData");
					Iterator ite=lastMoniData.keys();
					while(ite.hasNext()){
						JSONObject monidata=(JSONObject)lastMoniData.get(ite.next().toString());
						String city=monidata.get("city").toString();
						HSSFSheet sheet=wb.getSheet(city);
						String record=sheet.getRow(0).getCell(9).toString();
						int recordcount=Integer.parseInt(record.substring(record.indexOf(":")+1));
						HSSFRow row=sheet.getRow(recordcount+2);
						row.getCell(0).setCellValue(nowdt);
						row.getCell(1).setCellValue(date);
						row.getCell(2).setCellValue(getValue(monidata,"AQI"));
						row.getCell(3).setCellValue(getValue(monidata,"quality"));
						row.getCell(4).setCellValue(getValue(monidata,"PM2.5Hour"));
						row.getCell(5).setCellValue(getValue(monidata,"PM2.5Day"));
						row.getCell(6).setCellValue(getValue(monidata,"PM10Hour"));
						row.getCell(7).setCellValue(getValue(monidata,"lat"));
						row.getCell(8).setCellValue(getValue(monidata,"lon"));
						sheet.getRow(0).getCell(9).setCellValue("record:"+(recordcount+1));
					}
				}
				
				OutputStream excelgovout = new FileOutputStream(excelPath+citykey+nowdate+".xls");
		        wb.write(excelgovout);
				}else{
					errorMsg=jso.toString();
				}
			} catch (Exception e) {
				errorMsg=e.getMessage();
			}
			
			Log.info(errorMsg);
			return errorMsg;
	}

	private static String getValue(JSONObject jso, String key) {
		if (jso.has(key)) {
			try {
				return jso.get(key).toString();
			} catch (JSONException e) {
				e.printStackTrace();
				return "NaN";
			}
		} 
		return "NaN";
	}
	
	public static String readFile(String filename) {
		BufferedReader in = UtilsVP.openReadFile(filename);
		String line;
		StringBuilder sb = new StringBuilder();
		
		while ((line = UtilsVP.readln(in)) != null) {
			if (UtilsVP.notEmptyAndNoComment(line)) {
				sb.append(line);
			}
		}
		return sb.toString();
	}
	public static void main(String[] args) {
		try {
		AQIService as=new AQIService();
			
			as.exportAQI("shanghai");
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
	}
	
}


